//
//  MBProgressHUD+Extension.swift
//  TodayNews
//
//  Created by monkey on 2020/2/8.
//  Copyright © 2020 itcast. All rights reserved.
//

import MBProgressHUD

extension MBProgressHUD
{
    /// 展示提示信息
    public class func showTips(text: String, sourceView: UIView? = nil) -> Void
    {
        showHUD(text: text, view: sourceView, isAutomaticHide: true)
    }

    /// 展示错误提示
    public class func showErrorTips(text: String, sourceView: UIView? = nil) -> Void
    {
        showHUD(text: text, icon: "error.png", view: sourceView, isAutomaticHide: true)
    }

    /// 展示成功提示
    public class func showSuccessTips(text: String, sourceView: UIView? = nil) -> Void
    {
        showHUD(text: text, icon: "success.png", view: sourceView, isAutomaticHide: true)
    }
    
    /// 展示进度
    public class func showProgressHUD(text: String, sourceView: UIView? = nil) -> Void
    {
        showHUD(text: text, view: sourceView, isAutomaticHide: false)
    }
    
    /// 隐藏HUD
    public class func hideHUD(sourceView: UIView? = nil) -> Void
    {
        guard let view = (sourceView != nil ? sourceView : UIApplication.shared.keyWindow) else {
            return
        }

        hide(for: view, animated: true)
    }
    
    /// 展示提示框
    /// - Parameters:
    ///   - text: 文字
    ///   - icon: 图片名
    ///   - view: 容器视图
    ///   - isAutomaticHide: 是否自动隐藏
    private class func showHUD(text: String,icon: String? = nil, view: UIView? = nil, isAutomaticHide: Bool = true) -> Void
    {
        guard let sourceView = (view != nil ? view : UIApplication.shared.keyWindow) else {
            return
        }
        
        hideHUD(sourceView: sourceView)
        
        let HUD = MBProgressHUD.showAdded(to: sourceView, animated: true)
        if let icon = icon {
            // 显示图片
            HUD.mode = .customView
            let path = String(format: "MBProgressHUD.bundle/%@", icon)
            HUD.customView = UIImageView(image: UIImage(named: path))
            HUD.minSize = CGSize(width: 120, height: 120)
        } else {
            // 显示文字
            HUD.mode = isAutomaticHide ? .text : .indeterminate
            HUD.minSize = isAutomaticHide ? CGSize(width: TodayNews_Screen_Width - 96, height: 60) : CGSize(width: 120, height: 120)
        }
        
        HUD.contentColor = UIColor.white
        HUD.animationType = .zoom // 动画模式
        HUD.label.font = UIFont.systemFont(ofSize: 17) // 文字大小
        HUD.label.textColor = UIColor.white // 文字颜色
        HUD.label.text = text // 提示文字
        HUD.bezelView.layer.cornerRadius = 8.0; // 圆角半径
        HUD.bezelView.layer.masksToBounds = true
        HUD.bezelView.color = UIColor(white: 0, alpha: 0.6)// 提示框背景色
        HUD.bezelView.style = .solidColor  // 显示样式
        HUD.removeFromSuperViewOnHide = true; // 隐藏时候从父控件中移除
        HUD.backgroundColor = UIColor(white: 0, alpha: 0.3) // 蒙板背景色
        isAutomaticHide ? HUD.hide(animated: true, afterDelay: 2.0) : ()
    }
}
